#!/usr/bin/env python3
"""
Elasticsearch索引设计和映射配置
小红书内容推荐系统
"""

from elasticsearch import Elasticsearch
from datetime import datetime
import json

class ESIndexManager:
    """ES索引管理器"""
    
    def __init__(self, es_host="http://localhost:9200"):
        self.es = Elasticsearch([es_host])
        self.index_name = "content_recommend"
    
    def create_index_mapping(self):
        """创建内容推荐索引的映射"""
        mapping = {
            "settings": {
                "number_of_shards": 3,
                "number_of_replicas": 1,
                "analysis": {
                    "analyzer": {
                        "chinese_analyzer": {
                            "type": "custom",
                            "tokenizer": "ik_max_word",
                            "filter": ["lowercase", "stop"]
                        },
                        "chinese_smart": {
                            "type": "custom", 
                            "tokenizer": "ik_smart",
                            "filter": ["lowercase", "stop"]
                        }
                    }
                },
                "index": {
                    "max_result_window": 10000,
                    "refresh_interval": "30s"
                }
            },
            "mappings": {
                "properties": {
                    # 基础内容信息
                    "content_id": {
                        "type": "integer"
                    },
                    "title": {
                        "type": "text",
                        "analyzer": "chinese_analyzer",
                        "search_analyzer": "chinese_smart",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "description": {
                        "type": "text",
                        "analyzer": "chinese_analyzer",
                        "search_analyzer": "chinese_smart"
                    },
                    "author_id": {
                        "type": "integer"
                    },
                    "author_nickname": {
                        "type": "keyword"
                    },
                    
                    # 标签信息（数组）
                    "tag_ids": {
                        "type": "integer"  # ES会自动识别数组
                    },
                    "tag_names": {
                        "type": "keyword"
                    },
                    
                    # 状态和时间
                    "status": {
                        "type": "integer"
                    },
                    "created_at": {
                        "type": "date",
                        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
                    },
                    "published_at": {
                        "type": "date",
                        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
                    },
                    
                    # 互动数据
                    "view_count": {
                        "type": "integer"
                    },
                    "like_count": {
                        "type": "integer"
                    },
                    "comment_count": {
                        "type": "integer"
                    },
                    "share_count": {
                        "type": "integer"
                    },
                    "collect_count": {
                        "type": "integer"
                    },
                    
                    # 媒体信息
                    "media_urls": {
                        "type": "keyword"
                    },
                    "media_types": {
                        "type": "keyword"
                    },
                    "first_image_url": {
                        "type": "keyword"
                    },
                    
                    # 热度计算字段
                    "hot_score": {
                        "type": "float"
                    },
                    "time_score": {
                        "type": "float"
                    },
                    
                    # 是否置顶
                    "is_top": {
                        "type": "boolean"
                    },
                    
                    # 地理位置信息
                    "location": {
                        "type": "geo_point"
                    },
                    "city": {
                        "type": "keyword"
                    },
                    "district": {
                        "type": "keyword"
                    },
                    "address": {
                        "type": "keyword"
                    },
                    "location_precision": {
                        "type": "keyword"
                    }
                }
            }
        }
        return mapping
    
    def create_index(self):
        """创建索引"""
        try:
            if self.es.indices.exists(index=self.index_name):
                print(f"索引 {self.index_name} 已存在")
                return True
            
            mapping = self.create_index_mapping()
            response = self.es.indices.create(
                index=self.index_name,
                body=mapping
            )
            print(f"索引 {self.index_name} 创建成功")
            return True
            
        except Exception as e:
            print(f"创建索引失败: {e}")
            return False
    
    def delete_index(self):
        """删除索引"""
        try:
            if self.es.indices.exists(index=self.index_name):
                self.es.indices.delete(index=self.index_name)
                print(f"索引 {self.index_name} 删除成功")
            return True
        except Exception as e:
            print(f"删除索引失败: {e}")
            return False

if __name__ == "__main__":
    # 测试索引创建
    manager = ESIndexManager()
    manager.create_index()
